<template>
    <div class="colle-detail-content" v-if="loadingType">
        <div class="colleLeftCon">
            <div class="coll-detail-left-bigimg">
                    <img-box :imgs="[dtData.nftImage]" @click="showVideo" />
                    <div class="sell-status yugao" v-if="dtData.sellStatus==0">
                    PREVIEW
                    </div>
                    <div class="sell-status jinxingzhong" v-else-if="dtData.sellStatus==10 && dtData.sellModel==1"> <!--拍卖中-->
                        <!-- <i class="iconfont icon-shijian"></i> -->
                        IN AUCTION
                        <!-- Processing End {{dtData.endTime || '--'}} -->
                    </div>
                    <div class="sell-status jinxingzhong"  v-else-if="dtData.sellStatus==10 && dtData.sellModel==0"><!--出售中-->
                        <!-- <i class="iconfont icon-shijian"></i> -->
                        SELLING
                        <!-- End {{dtData.endTime || '--'}} -->
                    </div>
                    <div class="sell-status jieshu" v-else-if="dtData.sellStatus==20"><!--结束-->
                        Over
                    </div>
                    <div class="sell-status" v-else>
                        VIEW
                    </div>
            </div>
            <div class="redeemable-view"  v-if="dtData.nftType==8"  @click="btnGoods"  v-t="'collection.text2'">View Redeemable Items</div>
        </div>
        <div class="colleRightCon">
            <div class="scoll-view">
                    <div class="stitle">{{dtData.nftName}}</div>
                    <div class="introduce">{{dtData.nftDescription}}</div>

                    <template v-if="dtData.onSale">
                        <div class="price">
                            <div><img src="/images/bicon1.png" alt=""></div> 
                            <template v-if="dtData.sellModel==1">
                                <b>{{dtData.ethAmount.decimalFourString}}</b>（${{dtData.usdAmount.decimalTwoString}}）
                            </template>
                            <template v-else>
                                <b>{{(parseFloat(dtData.buyAmount.num) * rateObj.exhToCxt).toFixed(4)}}</b>（${{dtData.buyAmount.decimalTwoString}}）
                            </template>
                        </div>
                    </template>
                    <template v-else>
                        <div class="price" v-if="dtData.buyAmount && dtData.buyAmount.num>0"> <!--说明已经交易过-->
                            <div v-if="rateObj.exhToCxt"><img src="/images/bicon1.png" alt=""></div> 
                            <b v-if="rateObj.exhToCxt">{{(parseFloat(dtData.buyAmount.num) * rateObj.exhToCxt).toFixed(4)}}</b>（${{dtData.buyAmount.decimalTwoString}}）
                        </div>
                    </template>

                            <div class="user-view"> 
                                <div class="item" :style="{width:dtData.nftType!=5?'48%':'100%'}">
                                    <div class="title" v-t="'collection.text1'">TITLE HOLDING</div>
                                    <div class="dtname">{{dtData.ownerName||'--'}}</div>
                                </div>
                                <div class="line"></div> 
                                <div class="item on" @click="btnUrl" v-if="dtData.nftType!=5" :style="{width:'48%'}" >
                                        {{dtData.nftType==1?'Landmark':(dtData.nftType==8?'Goods':(dtData.nftType==3?'Prop':'Other'))}}
                                </div>
                        </div>
                    <div class="chainInfoBox">
                        <chain-info :styleType='2' :info="dtData"/>
                    </div>
                   </div>
                
                    <template v-if="dtData.onSale"> <!--说明已经发起了直售或者竞拍-->
                        <template v-if="dtData.sellModel==1"> <!--竞拍-->
                            <div class="paimaiyugao" v-if="dtData.sellStatus==0"><!--竞拍预告，显示取消按钮-->
                                <my-button text='Cancel Auction' :styleType="2" @click="cancelAuction"/>
                            </div>
                            <div class="paimaizhong" v-else-if="dtData.sellStatus==10"> <!--竞拍进行中，显示查看出价记录按钮-->
                                <my-button :text='text5' :styleType="2" @click="bidRecordFlag=true"/>
                                <bid-record v-if="bidRecordFlag" @close="bidRecordFlag=flase" :id='dtData.sellRecordId'/>
                            </div>
                            <div class="paimaijieshu" v-else-if="dtData.sellStatus==20" v-t="'collection.text3'"> <!--竞拍结束，显示获得者-->
                                End of auction
                            </div>
                        </template>
                        <template v-else-if="dtData.sellModel==0"> <!--直售-->
                            <div class="shoumaizhong" v-if="dtData.sellStatus==10"><!--出售中，显示取消出售按钮-->
                                <my-button text='Cancel A Sale' :styleType="2" @click="cancelSell"/>
                            </div>
                            <div class="shoumaijieshu" v-else-if="dtData.sellStatus==20" v-t="'collection.text4'"><!--出售结束,显示获得者-->
                                End of sale
                            </div>
                        </template>
                    </template>
                    <template v-else> <!--说明未发起售卖，显示售卖按钮-->
                        <div class="chushou-btn"> 
                            <!-- 广告位持有人钱包	adPlaceOwnerWallet  adPlaceLesseeExists 1存在 2不存在   广告位承租人钱包 adPlaceLesseeWallet 收益人 -->
                            <!-- 地标的售卖 用受益人和登录人的钱包来判断  其他的 用持有人和登录人 -->
                            <template v-if="dtData.nftType==1">
                                 <template v-if="dtData.exchanged==false&dtData.adPlaceLesseeExists==2&&dtData.ownerAddress!=null && dtData.ownerAddress.toLowerCase()==userInfo.walletAddress.toLowerCase()">
                                    <my-button :text="btnText1" :styleType="2" @click="saleSetFlag=true"/> 
                                    <my-button :text="btnText2" @click="btnGive"  :styleType="2"/>
                                </template>
                                <template v-else>
                                     <div class="nobtn" v-t="'collection.btn1'">Sell</div>
                                     <div  class="nobtn" v-t="'collection.btn2'">Give</div>
                                </template>
                            </template>
                            <template v-else>
                                <template v-if="dtData.ownerAddress!=null && dtData.ownerAddress.toLowerCase()==userInfo.walletAddress.toLowerCase()">
                                      <template v-if="dtData.exchanged==false">
                                        <my-button :text="btnText1" :styleType="2" @click="saleSetFlag=true"/> 
                                        <my-button :text="btnText2" @click="btnGive"  :styleType="2"/>
                                    </template>
                                    <template v-else>
                                        <div class="nobtn" v-t="'collection.btn1'">Sell</div>
                                        <div  class="nobtn" v-t="'collection.btn2'">Give</div>
                                    </template>
                                </template>
                            </template>
                            <set-goods-sale v-if="saleSetFlag" @refresh="getDetail" @close="saleSetFlag=false" :bornid="id"/>
                        </div>
                    </template>
           
        </div>
    </div>
</template>

<script>
import { reactive,toRefs,getCurrentInstance,onMounted,computed,inject} from 'vue'
import {useRoute,useRouter} from 'vue-router'
import { useStore } from 'vuex'
import {CheckboxGroup as vanCheckboxGroup} from 'vant'
import Title from '@/components/title.vue'
import twoTitle from '@/components/twoTitle.vue'
import imgBox from '@/components/imgBox.vue'
import chainInfo from '@/components/chainInfo.vue'
import uvPvVisits from '@/components/uvPvVisits.vue'
import myButton from '@/components/myButton.vue'
//import bidRecord from './bidRecord.vue'
import cutBorderBox from '@/components/cutBorderBox.vue' 
import myDailog from '@/components/myDailog.vue' 
import Success from '@/components/success.vue' 
import myDatetimePicker from '@/components/myDatetimePicker.vue'
//import detailPublic from './detailPublic.vue'
//import lookSelf from './lookSelf.vue'
//import lookOther from './lookOther.vue'
import setGoodsSale from './setGoodsSale.vue'
import bidRecord from '@/components/bidRecord.vue'
import { toast,myJsDailog,H5CallAPPFuction } from '@/utils/common'
import { useI18n } from 'vue-i18n'

export default {
    components:{
       Title,
       twoTitle,
       imgBox,
       //vanCheckboxGroup,
       myDailog,
       chainInfo,
       //uvPvVisits,
       //detailPublic,
       myButton,
       //bidRecord,
       //cutBorderBox,
       Success,
       setGoodsSale,
       bidRecord
       //myDatetimePicker,
       //lookSelf,
      // lookOther
    },
    props:{
        detail:Object,
        id:''
    },
    setup(props,context){
        const router = useRouter()
        const route = useRoute()
        const store = useStore()
        const {proxy} = getCurrentInstance()
        const {t} = useI18n()
        const detailPopClose = inject('detailPopClose')
        const state = reactive({
            userInfo:computed(()=>store.state.base.userInfo),
            //showFlag:false,
            showFlag2:false,
            showFlag3:false,
            showtype:1, // 1显示出售方式弹窗，2显示一口价弹窗，3显示一口价授权弹窗，4显示拍卖弹窗，5显示成功弹窗，
            hbtypes:[],
            auStartTime:'2021-01-02 09:40',
            auEndTime:'',
            dtData:null,
            loadingType:false,
            saleSetFlag:false,
            bidRecordFlag:false,
            btnText1:t('collection.btn1'),
            btnText2:t('collection.btn2'),
            text5:t('collection.text5'),
            rateObj:{} // 兑换比例
        })
    
        onMounted(()=>{
            store.commit('collection/set_nftdDetail',{}) // 清空
            if(props.id){
               getDetail()
            }else{
                store.commit('collection/set_nftdDetail',props.detail)
            }
            setTimeout(() => {
                if(state.dtData){
                 store.dispatch('base/add_visit_object',{
                        objectId:state.dtData.relationId,
                        visitTypeCode:parseInt(state.dtData.nftType),
                        walletAddress:state.userInfo.walletAddress
                    }).then(res =>{
                    })
                }
              }, 1000);
          
            // 定义tradeResults方法，供app调用(app交易处理完成后调用)
            window['tradeResults'] = function (result) { // result：{"success":0,"msg":""}
                if(!result){
                    return toast('No Processing Result') // 没有处理结果
                }
                const rt = JSON.parse(result)
                if(rt.success==0){ // 取消出错了
                    toast(rt.msg)
                }else{
                    toast('Cancellation Succeeded！')
                    setTimeout(() => {
                         getDetail()
                    }, 1500);
                    detailPopClose() // 关闭详情弹窗
                } 
            }


            // 兑换比例
            store.dispatch('base/get_exchange_rate',{walletAddress:state.userInfo.walletAddress})
            .then(res =>{
                state.rateObj = res.data
            })
        })
        const getDetail = ()=>{ //刷新
            store.dispatch('collection/get_collection_detail',{
                    bornId:props.id
                }).then(res =>{
                    if(!res.success){
                        return toast('Failed To Get Detailed Data')
                    }else{
                        state.dtData = res.data
                    }
                    state.loadingType = true
                })
                 store.dispatch('ad/add_ad_place_pv',{
                                adPlaceId:props.id,
                                walletAddress:state.userInfo.walletAddress || ''
                     }) 
          }

        const cancelAuction = ()=>{ // 取消拍卖
            const appParams = {
                cancelType:2,
                ...state.dtData
            }
            console.log("appParams:",appParams)
            try {
                // 拍卖出价处理: 调用app的auctionBid方法，传入参数交由app处理，H5只接受处理结果（tradeResults方法接收）
                H5CallAPPFuction('cancleSale',JSON.stringify(appParams)) 
            } catch (error) {
                console.log('调用app失败')
            }
            // myJsDailog({
            //     message:'Please confirm whether to cancel the auction'
            // },()=>{
            //     store.dispatch('sell/camcel_sale',{
            //         sellRecordId:state.dtData.sellRecordId
            //     }).then(res=>{
            //         if(res.success){
            //             toast('Cancel Successfully！')
            //         }else{
            //             toast(res.message)
            //         }
            //     })
            // })
        }
        const cancelSell = ()=>{ // 取消售卖
            const appParams = {
                cancelType:1,
                ...state.dtData
            }
            console.log("appParams:",appParams)
            try {
                // 拍卖出价处理: H5只接受处理结果（tradeResults方法接收）
                H5CallAPPFuction('cancleSale',JSON.stringify(appParams)) 
            } catch (error) {
                console.log('调用app失败')
            }
            // myJsDailog({
            //     message:'Please confirm whether to cancel the sale'
            // },()=>{
            //     store.dispatch('sell/camcel_sale',{
            //         sellRecordId:state.dtData.sellRecordId
            //     }).then(res=>{
            //         if(res.success){
            //             toast('Cancel Successfully！')
            //         }else{
            //             toast(res.message)
            //         }
            //     })
            // })
        }

        
        
          const btnGive = ()=>{ // 赠送
            try {
                H5CallAPPFuction('transferNFT',JSON.stringify({...state.dtData,...{bornId:props.id}})) 
            } catch (error) {
                console.log('调用app失败')
            }
         }

          const btnUrl = ()=>{ //跳转详情
           
            if(state.dtData.nftType==8){
                router.push({path:'/goods/'+state.dtData.relationId})
            }
             if(state.dtData.nftType==3){ 
                router.push({path:'/ad/detailProp',query:{arPropId:state.dtData.relationId,propTemplateId:null,exchanged:null}})
            }
            if(state.dtData.nftType==1){
                  try {
                  H5CallAPPFuction('showLandmarkDetial',state.dtData.relationId) 
                } catch (error) {
                    console.log('调用app失败')
                }
            }
         }
            const btnGoods = ()=>{ //商品详情
              router.push({path:'/goods/'+state.dtData.relationId})
            }
           const showVideo = ()=>{ //商品详情
                 try {
                     console.log({resourceUrl: state.dtData.nftImage})
                  H5CallAPPFuction('showVideo',JSON.stringify({resourceUrl: state.dtData.nftImage})) 
                } catch (error) {
                    console.log('调用app失败')
                }
            }
         
        return{
            ...toRefs(state),
            cancelAuction,
            cancelSell,
            detailPopClose,
            btnGive,
            btnUrl,
            getDetail,
            btnGoods,
            showVideo
        }
    }
}
</script>

<style lang="scss" scoped>
    .colle-detail-content{
        display: flex;
        width: 100%;
        height: 100%;
        line-height: normal;
        font-size: 28px;
        font-weight: 500;
        color: #FFFFFF;
        overflow: hidden;
        overflow-x: auto;
        padding: 20px 20px 0px 20px;
        font-family: Poppins-Medium, Poppins;
        font-weight: 500;
        color: #FFFFFF;
        line-height: normal;
        font-size: 28px;
        .colleLeftCon{
            display: flex;
            flex-flow: column;
            width: 530px;
            height: 100%;
            background-image: url(/images/adRelease/box-bg.png);
            background-position: center;
            background-size: 100% 100%;
            background-repeat: no-repeat;
            padding:30px;
            position: relative;
            .redeemable-view{
                color: #67F8FF;
                 font-size: 28px;
                 text-align: center;
                 padding-top:30px;
            }
            .coll-detail-left-bigimg{
                position: relative;
                flex: 1;
                width: 100%;
                z-index: 10;
                .sell-status{
                    display: flex;
                    align-items: center;
                    position: absolute;
                    z-index: 10;
                    width: 100%;
                    height: 70px;
                    left: 0;
                    bottom: 0;
                    background: linear-gradient(225deg, #FF3300 0%, #841A00 100%);
                    padding:0 20px;
                    font-size:24px;
                    &.yugao{
                         background: linear-gradient(225deg, #FF3300 0%, #841A00 100%);
                    }
                    &.chushouzhong,.jinxingzhong{
                        background: linear-gradient(225deg, #00A3FF 0%, #004AD9 100%);
                    }
                    &.jieshu{
                        background: linear-gradient(225deg, #B1B1B1 0%, #474747 100%);
                       // background: rgba(0,0,0,0.7);
                    }
                    &.paimaizhong{
                        background: linear-gradient(225deg, #00A3FF 0%, #004AD9 100%);
                    }
                    i{
                        font-weight: bold;
                        margin: 0 5px 0 0;
                    }
                }
            }
        }
        .colleRightCon{
            flex: 1;
            height: 100%;
            padding:30px;
            max-width:60%;
            font-family: Poppins-Medium, Poppins;
            font-weight: 500;
            color: #ffffff80;
            line-height: normal;
            font-size: 22px;
            background-image: url(/images/adRelease/sbg.png);
            background-position: center;
            background-size: 100% 100%;
            background-repeat: no-repeat;
            position: relative;
            margin-left:30px;
                .scoll-view{
                overflow: hidden;
                overflow-y: auto;
                -webkit-overflow-scrolling:touch;
                height:90%;
                width:100%;
            }
         .user-view{
                display: flex;
                justify-content: space-between;
                position: relative;
                margin-top:20px;
                .line{
                    position: absolute;
                    width:1px;
                    height:60px;
                    left:50%;
                    top:50%;
                    margin-left:-5px;
                    margin-top:-30px;
                }
                .item{
                    width:48%;
                    padding: 5px 0;
                    text-align: center;
                    background-color: #67F8FF50;
                   // background: rgba(103,248,255,0.2000);
                    border:1px solid #67F8FF;
                }.on{
                    padding-top:20px;
                }
                .title{
                    font-size:20px;
                    color:#ffffff50;
                }
                .dtname{
                    font-size:24px;
                    color:#67F8FF;
                }
        }
            .stitle{
                font-size: 28px;
            }
            .introduce{
                color: #779EC8;
                padding: 10px 0 0 0;
            }
            .price{
                display: flex;
                font-size: 26px;
                align-items: center;
                padding: 20px 0 0 0;
                color: #5781BE;
                img{
                    display: block;
                    float: left;
                    width: 20px;
                    margin: 3px 10px 0 0;
                }
                b{
                    font-size: 36px;
                    font-weight: 500;
                    color: #fff;
                }
            }
            .bottom-view-line{
                display: flex;
                justify-content: flex-start;
            }
            .chainInfoBox{
                background: rgba(103,248,255,0.1);
                margin: 20px 0;
                padding:20px;
            }
            .chushou-btn{
                width: 420px;
                padding-top:10px;
                display: flex;
                justify-content: space-around;
                .nobtn{
                    width:180px;
                    height:60px;
                    line-height:60px;
                    text-align: center;
                    font-size:26px;
                    background-color: #999;
                    color:#fff;
                }
            }
            .paimaizhong,.paimaiyugao,.shoumaizhong{
                width: 300px;
                margin: 20px 0 0 0;
            }
        }
    }
</style>